<template>
	<view class="add-record-container">
		<!-- 头部导航 -->
		<view class="nav-header">
			<view class="nav-back" @click="handleBack">
				<text class="back-icon">‹</text>
			</view>
			<text class="nav-title">记一笔</text>
			<view class="nav-placeholder"></view>
		</view>

		<!-- 主要内容 -->
		<view class="main-content">
			<!-- 类型选择 -->
<!-- 			<view class="type-section">
				<view class="type-option" :class="{ active: formData.type === 0 }" @click="changeType(0)">
					<view class="type-icon expense">
						<text class="type-symbol">-</text>
					</view>
					<text class="type-label">支出</text>
				</view>
				<view class="type-option" :class="{ active: formData.type === 1 }" @click="changeType(1)">
					<view class="type-icon income">
						<text class="type-symbol">+</text>
					</view>
					<text class="type-label">收入</text>
				</view>
				<view class="type-option" :class="{ active: formData.type === 2 }" @click="changeType(2)">
					<view class="type-icon transfer">
						<text class="type-symbol">⇄</text>
					</view>
					<text class="type-label">转账</text>
				</view>
				<view class="type-option" :class="{ active: formData.type === 3 }" @click="changeType(3)">
					<view class="type-icon debt">
						<text class="type-symbol">⚡</text>
					</view>
					<text class="type-label">债务</text>
				</view>
			</view> -->

			

			<!-- 分类选择 -->
			<view class="category-section">
				<!-- 一级分类 -->
				<scroll-view scroll-x class="category-scroll">
					<view class="category-tabs">
						<view v-for="topCategory in topLevelCategories" :key="topCategory.id" class="category-tab"
							:class="{ active: activeTopLevelId === topCategory.id }"
							@click="handleTopLevelClick(topCategory)">
							<view class="tab-icon">
								<text class="icon">{{ getCategoryIcon(topCategory.name) }}</text>
							</view>
							<text class="tab-name">{{ topCategory.name }}</text>
						</view>
					</view>
				</scroll-view>

				<!-- 二级分类 -->
				<view class="sub-category-section"
					v-if="activeTopLevel && activeTopLevel.children && activeTopLevel.children.length > 0">
					<scroll-view scroll-x class="sub-category-scroll">
						<view class="sub-category-tabs">
							<view v-for="subCategory in activeTopLevel.children" :key="subCategory.id"
								class="sub-category-tab" :class="{ active: activeSecondLevelId === subCategory.id }"
								@click="handleSecondLevelClick(subCategory)">
								<view class="tab-icon">
									<text class="icon">{{ getCategoryIcon(subCategory.name) }}</text>
								</view>
								<text class="tab-name">{{ subCategory.name }}</text>
							</view>
						</view>
					</scroll-view>

					<!-- 三级分类 -->
					<view class="third-category-section"
						v-if="activeSecondLevel && activeSecondLevel.children && activeSecondLevel.children.length > 0">
						<view class="third-category-grid">
							<view v-for="thirdCategory in activeSecondLevel.children" :key="thirdCategory.id"
								class="third-category-item"
								:class="{ active: formData.categoryId === thirdCategory.id }"
								@click="selectThirdCategory(thirdCategory)">
								<view class="item-icon">
									<text class="icon">{{ getCategoryIcon(thirdCategory.name) }}</text>
								</view>
								<text class="item-name">{{ thirdCategory.name }}</text>
							</view>
						</view>
					</view>
				</view>
			</view>
			
			<!-- 金额输入 -->
			<view class="amount-section">
				<text class="currency-symbol">¥</text>
				<input v-model="formData.amount" class="amount-input" type="digit" placeholder="0.00" maxlength="10"
					focus @input="onAmountInput" />
			</view>
			
			<!-- 其他信息 -->
			<view class="info-section">
				<!-- 日期 -->
				<view class="info-item" @click="showDatePicker = true">
					<text class="info-label">今天</text>
					<view class="info-value">
						<text class="selected-date">{{ formData.recordDate }}</text>
						<text class="arrow-icon">›</text>
					</view>
				</view>

				<!-- 账户 -->
				<view class="info-item">
					<text class="info-label">账户</text>
					<view class="info-value">
						<text class="selected-account">无账户</text>
						<text class="arrow-icon">›</text>
					</view>
				</view>

				<!-- 备注 -->
				<view class="info-item remark-item">
					<text class="info-label">备注</text>
					<input v-model="formData.remark" class="remark-input" placeholder="添加备注" maxlength="100" />
				</view>

				<!-- 扩展选项 -->
				<view class="expand-options">
					<view class="option-item">
						<text class="option-label">不报销</text>
						<switch class="option-switch" />
					</view>
					<view class="option-item">
						<text class="option-label">附件</text>
						<text class="option-value">0</text>
					</view>
					<view class="option-item">
						<text class="option-label">优惠</text>
						<text class="option-value">¥0.00</text>
					</view>
				</view>
			</view>

			<!-- 数字键盘 -->
			<view class="keyboard-section">
				<view class="keyboard-row">
					<button class="key-btn" @click="inputNumber('1')">1</button>
					<button class="key-btn" @click="inputNumber('2')">2</button>
					<button class="key-btn" @click="inputNumber('3')">3</button>
					<button class="key-btn operator" @click="inputOperator('+')">+</button>
				</view>
				<view class="keyboard-row">
					<button class="key-btn" @click="inputNumber('4')">4</button>
					<button class="key-btn" @click="inputNumber('5')">5</button>
					<button class="key-btn" @click="inputNumber('6')">6</button>
					<button class="key-btn operator" @click="inputOperator('-')">-</button>
				</view>
				<view class="keyboard-row">
					<button class="key-btn" @click="inputNumber('7')">7</button>
					<button class="key-btn" @click="inputNumber('8')">8</button>
					<button class="key-btn" @click="inputNumber('9')">9</button>
					<button class="key-btn operator" @click="inputOperator('×')">×</button>
				</view>
				<view class="keyboard-row">
					<button class="key-btn" @click="inputNumber('0')">0</button>
					<button class="key-btn" @click="inputNumber('.')">.</button>
					<button class="key-btn delete" @click="deleteLast">⌫</button>
					<button class="key-btn operator" @click="inputOperator('÷')">÷</button>
				</view>
			</view>

			<!-- 底部按钮 -->
			<view class="bottom-actions">
				<button class="action-btn cancel" @click="handleBack">取消</button>
				<button class="action-btn save" :class="{ disabled: !isFormValid }" :disabled="!isFormValid"
					@click="handleSave">
					<text class="button-text">保存</text>
				</button>
			</view>
		</view>

		<!-- 日期选择器 -->
		<uni-datetime-picker ref="datePicker" type="date" :value="formData.recordDate" @change="onDateChange"
			v-if="showDatePicker" />
	</view>
</template>

<script>
	import {
		mapActions,
		mapGetters
	} from 'vuex'

	export default {
		data() {
			return {
				showDatePicker: false,
				activeTopLevelId: 1, // 默认选中支出
				activeSecondLevelId: null,
				formData: {
					type: 0, // 0-支出, 1-收入, 2-转账, 3-债务
					amount: '',
					categoryId: null,
					recordDate: this.getToday(),
					remark: '',
					accountId: null
				}
			}
		},

		computed: {
			...mapGetters([
				'categoryTree',
				'treeExpenseCategories',
				'treeIncomeCategories',
				'treeTransferCategories',
				'treeLoanCategories'
			]),

			// ✅ 安全获取分类数据
			safeExpenseCategories() {
				return this.expenseCategories || this.treeExpenseCategories;
			},
			safeIncomeCategories() {
				return this.incomeCategories || this.treeIncomeCategories;
			},
			topLevelCategories() {
				// 🆕 优先使用分类树数据
				if (this.categoryTree && this.categoryTree.length > 0) {
					return this.categoryTree;
				}

				return [{
						id: 1,
						name: '支出',
						children: this.safeExpenseCategories
					},
					{
						id: 2,
						name: '收入',
						children: this.incomeCategories || []
					},
					{
						id: 3,
						name: '转账',
						children: []
					},
					{
						id: 4,
						name: '债务',
						children: []
					}
				];
			},
			//分类数据（ 从 Vuex 获取）
			categories() {
				return this.formData.type === 0 ? this.expenseCategories : this.incomeCategories
			},

			activeTopLevel() {
				if (!this.activeTopLevelId) return null;
				return this.topLevelCategories.find(cat => cat.id === this.activeTopLevelId) || null;
			},

			activeSecondLevel() {
				if (!this.activeTopLevel || !this.activeSecondLevelId) return null;
				return this.activeTopLevel.children?.find(cat => cat.id === this.activeSecondLevelId) || null;
			},

			isFormValid() {
				return this.formData.amount &&
					parseFloat(this.formData.amount) > 0 &&
					this.formData.categoryId
			}
		},

		methods: {
			...mapActions(['addRecord', 'loadCategoryTree']),

			getToday() {
				const today = new Date()
				return today.toISOString().split('T')[0]
			},
			// ✅ 默认分类数据（fallback）
			getDefaultCategories() {
				return {
					expense: [{
							id: 101,
							name: '购物消费',
							type: 0
						},
						{
							id: 102,
							name: '食品餐饮',
							type: 0
						},
						{
							id: 103,
							name: '出行交通',
							type: 0
						}
					]
				};
			},

			setDefaultCategory() {
				this.$nextTick(() => {
					// 确保数据已加载
					if (!this.formData.categoryId && this.safeExpenseCategories.length > 0) {
						this.formData.categoryId = this.safeExpenseCategories[0].id;
						console.log('设置默认分类ID:', this.formData.categoryId);
					} else if (!this.formData.categoryId) {
						// 如果所有分类都为空，设置一个安全的默认值
						this.formData.categoryId = 101;
						console.log('使用默认分类ID:', this.formData.categoryId);
					}
				});
			},

			handleBack() {
				uni.navigateBack();
			},

			changeType(type) {
				this.formData.type = type
				this.formData.categoryId = null
				this.activeTopLevelId = type + 1 // 根据类型设置默认顶级分类
				this.activeSecondLevelId = null
			},

			handleTopLevelClick(category) {
				this.activeTopLevelId = category.id
				this.activeSecondLevelId = null

				// 默认选中第一个子分类
				if (category.children && category.children.length > 0) {
					this.activeSecondLevelId = category.children[0].id
					this.formData.categoryId = category.children[0].id
				}
			},

			// 🆕 添加缺失的方法：处理二级分类点击
			handleSecondLevelClick(category) {
				this.activeSecondLevelId = category.id

				// 如果二级分类有子分类，默认选中第一个三级分类
				if (category.children && category.children.length > 0) {
					this.formData.categoryId = category.children[0].id
				} else {
					// 如果没有三级分类，直接选择二级分类
					this.formData.categoryId = category.id
				}
			},

			// 🆕 添加缺失的方法：选择三级分类
			selectThirdCategory(category) {
				this.formData.categoryId = category.id
			},

			selectCategory(category) {
				this.formData.categoryId = category.id
				// 如果是二级分类，设置activeSecondLevelId
				if (category.parentId === this.activeTopLevelId) {
					this.activeSecondLevelId = category.id
				}
			},

			onAmountInput(e) {
				let value = e.detail.value
				value = value.replace(/[^\d.]/g, '')

				const dotIndex = value.indexOf('.')
				if (dotIndex !== -1) {
					value = value.substring(0, dotIndex + 1) + value.substring(dotIndex + 1).replace(/\./g, '')
				}

				if (dotIndex !== -1) {
					const decimalPart = value.substring(dotIndex + 1)
					if (decimalPart.length > 2) {
						value = value.substring(0, dotIndex + 3)
					}
				}

				this.formData.amount = value
			},

			inputNumber(num) {
				if (this.formData.amount === '0' && num !== '.') {
					this.formData.amount = num
				} else {
					this.formData.amount += num
				}
			},

			inputOperator(op) {
				// 这里可以添加计算器功能
				console.log('操作符:', op)
			},

			deleteLast() {
				if (this.formData.amount.length > 0) {
					this.formData.amount = this.formData.amount.slice(0, -1)
				}
			},

			onDateChange(e) {
				this.formData.recordDate = e
				this.showDatePicker = false
			},

			getCategoryIcon(name) {
				const iconMap = {
					'支出': '💰',
					'收入': '💵',
					'转账': '🔄',
					'债务': '⚡',
					'购物消费': '🛒',
					'食品餐饮': '🍽️',
					'出行交通': '🚗',
					'酒店住宿': '🏨',
					'休闲娱乐': '🎮',
					'罚款赔偿': '⚖️',
					'理财支出': '📊',
					'慈善捐助': '❤️',
					'居家生活': '🏠',
					'文化教育': '📚',
					'送礼人情': '🎁',
					'健康医疗': '🏥',
					'早餐': '🌅',
					'午餐': '🌞',
					'晚餐': '🌙',
					'宵夜': '🌃',
					'零食': '🍿'
				}
				return iconMap[name] || '📁'
			},

			handleSave() {
				if (!this.isFormValid) {
					uni.showToast({
						title: '请填写完整信息',
						icon: 'none'
					})
					return
				}

				const submitData = {
					type: this.formData.type,
					amount: parseFloat(this.formData.amount),
					categoryId: this.formData.categoryId,
					recordDate: this.formData.recordDate,
					remark: this.formData.remark
				}

				this.addRecord(submitData).then(() => {
					uni.showToast({
						title: '保存成功',
						icon: 'success'
					})

					setTimeout(() => {
						uni.navigateBack()
					}, 1500)

				}).catch(error => {
					console.error('保存失败:', error)
					uni.showToast({
						title: error.message || '保存失败',
						icon: 'none'
					})
				})
			}
		},

		mounted() {
			console.log('开始加载分类数据...');

			this.loadCategoryTree().then(() => {
				console.log('分类树加载成功')
				this.setDefaultCategory();
			}).catch(error => {
				console.error('加载分类树失败:', error);
				// ✅ 即使加载失败也设置默认分类
				this.setDefaultCategory();
			});
		},


		onLoad(options) {
			if (options.type) {
				this.formData.type = parseInt(options.type)
				this.activeTopLevelId = this.formData.type + 1
			}
		}
	}
</script>

<style scoped>
	.add-record-container {
		min-height: 100vh;
		background: #f5f5f5;
	}

	/* 导航头部 */
	.nav-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 60rpx 30rpx 30rpx;
		background: white;
	}

	.back-icon {
		font-size: 60rpx;
		color: #333;
	}

	.nav-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
	}

	.nav-placeholder {
		width: 60rpx;
	}

	/* 类型选择 */
	.type-section {
		display: flex;
		background: white;
		padding: 30rpx;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.type-option {
		flex: 1;
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 20rpx;
	}

	.type-option.active .type-icon {
		background: #007AFF;
	}

	.type-option.active .type-label {
		color: #007AFF;
		font-weight: bold;
	}

	.type-icon {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-bottom: 15rpx;
		background: #f0f0f0;
		transition: all 0.3s;
	}

	.type-symbol {
		font-size: 36rpx;
		font-weight: bold;
		color: white;
	}

	.type-icon.income .type-symbol {
		color: #4ECDC4;
	}

	.type-icon.expense .type-symbol {
		color: #FF6B6B;
	}

	.type-icon.transfer .type-symbol {
		color: #45B7D1;
	}

	.type-icon.debt .type-symbol {
		color: #96CEB4;
	}

	.type-option.active .type-icon .type-symbol {
		color: white;
	}

	.type-label {
		font-size: 24rpx;
		color: #666;
	}

	/* 金额输入 */
	.amount-section {
		background: white;
		padding: 60rpx 30rpx;
		text-align: center;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.currency-symbol {
		font-size: 64rpx;
		color: #333;
		font-weight: bold;
	}

	.amount-input {
		font-size: 72rpx;
		font-weight: bold;
		color: #333;
		border: none;
		text-align: center;
		width: 100%;
		margin-top: 20rpx;
	}

	.amount-input::placeholder {
		color: #ccc;
	}

	/* 分类选择 */
	.category-section {
		background: white;
		margin-bottom: 20rpx;
	}

	.category-scroll {
		white-space: nowrap;
		padding: 30rpx 20rpx;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.category-tabs {
		display: inline-flex;
	}

	.category-tab {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 0 25rpx;
		min-width: 100rpx;
	}

	.category-tab.active .tab-icon {
		background: #007AFF;
		color: white;
	}

	.category-tab.active .tab-name {
		color: #007AFF;
		font-weight: bold;
	}

	.tab-icon {
		width: 70rpx;
		height: 70rpx;
		border-radius: 50%;
		background: #f0f0f0;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-bottom: 10rpx;
	}

	.tab-icon .icon {
		font-size: 32rpx;
	}

	.tab-name {
		font-size: 24rpx;
		color: #666;
	}

	.sub-category-section {
		padding: 20rpx 0;
	}

	.sub-category-scroll {
		white-space: nowrap;
		padding: 0 20rpx 20rpx;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.sub-category-tabs {
		display: inline-flex;
	}

	.sub-category-tab {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 0 20rpx;
		min-width: 90rpx;
	}

	.sub-category-tab.active .tab-icon {
		background: #4ECDC4;
		color: white;
	}

	.sub-category-tab.active .tab-name {
		color: #4ECDC4;
		font-weight: bold;
	}

	.third-category-section {
		padding: 20rpx;
	}

	.third-category-grid {
		display: grid;
		grid-template-columns: repeat(4, 1fr);
		gap: 30rpx;
	}

	.third-category-item {
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.third-category-item.active .item-icon {
		background: #45B7D1;
		color: white;
	}

	.third-category-item.active .item-name {
		color: #45B7D1;
		font-weight: bold;
	}

	.item-icon {
		width: 60rpx;
		height: 60rpx;
		border-radius: 50%;
		background: #f8f9fa;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-bottom: 10rpx;
	}

	.item-icon .icon {
		font-size: 28rpx;
		color: #666;
	}

	.item-name {
		font-size: 22rpx;
		color: #666;
		text-align: center;
	}

	/* 其他信息 */
	.info-section {
		background: white;
		margin-bottom: 20rpx;
	}

	.info-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.info-label {
		font-size: 32rpx;
		color: #333;
	}

	.info-value {
		display: flex;
		align-items: center;
	}

	.selected-date,
	.selected-account {
		font-size: 32rpx;
		color: #666;
		margin-right: 20rpx;
	}

	.arrow-icon {
		color: #999;
		font-size: 36rpx;
	}

	.remark-item {
		align-items: flex-start;
	}

	.remark-input {
		flex: 1;
		text-align: right;
		font-size: 32rpx;
		color: #333;
	}

	.expand-options {
		padding: 20rpx 30rpx;
	}

	.option-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 0;
	}

	.option-label {
		font-size: 28rpx;
		color: #666;
	}

	.option-value {
		font-size: 28rpx;
		color: #999;
	}

	/* 数字键盘 */
	.keyboard-section {
		background: white;
		padding: 20rpx;
	}

	.keyboard-row {
		display: flex;
		margin-bottom: 20rpx;
	}

	.key-btn {
		flex: 1;
		height: 100rpx;
		margin: 0 10rpx;
		background: #f8f9fa;
		border: none;
		border-radius: 8rpx;
		font-size: 36rpx;
		color: #333;
	}

	.key-btn.operator {
		background: #e9ecef;
		color: #007AFF;
	}

	.key-btn.delete {
		background: #ffe6e6;
		color: #ff6b6b;
	}

	/* 底部按钮 */
	.bottom-actions {
		display: flex;
		padding: 30rpx;
		background: white;
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
	}

	.action-btn {
		flex: 1;
		height: 100rpx;
		border: none;
		border-radius: 16rpx;
		font-size: 32rpx;
		font-weight: bold;
	}

	.action-btn.cancel {
		background: #f8f9fa;
		color: #666;
		margin-right: 20rpx;
	}

	.action-btn.save {
		background: #007AFF;
		color: white;
	}

	.action-btn.save.disabled {
		background: #ccc;
		color: #999;
	}
</style>